<!--
 * @Version: 1.0
 * @Autor:
 * @Date: 2021-03-15 10:59:39
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-04-27 14:39:15
 * @Description:
-->
<template>
  <div>
    <el-card v-loading="loading" class="app-container content_box" shadow="always">
      <div class="header_title_box">
        <h2>基本信息</h2>
      </div>
      <div>
        <el-form :ref="formName" :model="formFieldsData" :rules="rules" inline class="dialog-form-expand2">
          <el-form-item label="模板名称" :label-width="formLabelWidth" prop="name">
            <el-input v-model.trim="formFieldsData.name" :disabled="disabled" placeholder="请输入模板名称" autocomplete="off" clearable style="width:247px" />
          </el-form-item>
          <el-form-item label="客户选择" :label-width="formLabelWidth" prop="company_id">
            <el-select v-model="formFieldsData.company_id" :disabled="disabled" placeholder="请选择客户" filterable clearable style="width:247px">
              <el-option v-for="item in optionCompany" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="header_title_box">
        <h2 style="margin-right:50px">
          台阶费设置
        </h2>
        <div v-if="!disabled">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="addField">新增</el-button>
          <el-button v-if="selectedIdsFather.length>0" type="danger" size="mini" icon="el-icon-delete" @click="delField">批量删除</el-button>
        </div>
      </div>
      <div>
        <el-form ref="formData" :rules="model.rules" :model="model" class="">
          <el-table :data="model.fields" tooltip-effect="dark" style="width: 800px" border fit @selection-change="handleSelectMultiFather">
            <el-table-column v-if="!disabled" align="center" type="selection" width="55" />
            <el-table-column v-if="!disabled" align="center" label="操作" width="150">
              <template slot-scope="field">
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteField(field.row)" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="重量范围(lbs）">
              <template slot-scope="field" required>
                <el-form-item>
                  <el-col :span="11">
                    <el-form-item :prop="'fields.' + field.$index + '.min_weight'" :rules="model.rules.min_weight">
                      <el-input-number
                        v-model.trim="field.row.min_weight"
                        :disabled="field.row.disabled"
                        size="mini"
                        :precision="2"
                        placeholder="输入最小重量"
                        autocomplete="off"
                        clearable
                        :min="1"
                        :max="99999999"
                        :controls="false"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col class="line" :span="2">-</el-col>
                  <el-col :span="11">
                    <el-form-item :prop="'fields.' + field.$index + '.max_weight'" :rules="model.rules.max_weight">
                      <el-input-number
                        v-model.trim="field.row.max_weight"
                        :disabled="field.row.disabled"
                        size="mini"
                        :precision="2"
                        placeholder="输入最大重量"
                        autocomplete="off"
                        clearable
                        :min="Number(field.row.min_weight)+1"
                        :max="99999999"
                        :controls="false"
                      />
                    </el-form-item>
                  </el-col>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" label="费用(USD)/每件">
              <template slot-scope="field">
                <el-form-item :prop="'fields.' + field.$index + '.fee'" :rules="model.rules.fee">
                  <el-input
                    v-model.trim="field.row.fee"
                    :disabled="field.row.disabled"
                    size="mini"
                    placeholder="输入额度"
                    autocomplete="off"
                    clearable
                  />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
      <div class="footer-center">
        <el-button :type="type === 'info' ? 'primary' : 'default'" @click="handleCancelPath">{{ type === 'info' ? '返 回' : '取 消' }}</el-button>
        <el-button v-if="!disabled" type="primary" @click="handleSubmitNew">确 定</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import formOperate from '@/layout/mixin/formOperate'
import {
  companyList
} from '@/utils/publicData'
export default {
  name: 'BasicsOrderFeeConfigAdd',
  mixins: [formOperate],
  data() {
    return {
      loading: false,
      selectedIdsFather: [],
      id: '',
      formFieldsData: {
        name: '',
        company_id: ''
      },
      formName: 'orderFeeSettings',
      formLabelWidth: '150px',
      formVisible: false,
      outerVisible: false,
      optionCompany: [],
      rules: {
        name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
        company_id: [{ required: true, message: '请选择客户', trigger: 'blur' }]
      },
      model: {
        rules: {
          min_weight: [{ required: true, message: '必填字段', trigger: 'change' }, { pattern: /\d+(\.[0-9]{1,2}){0,1}$/, message: '只能输入数字', trigger: 'change' }],
          max_weight: [{ required: true, message: '必填字段', trigger: 'blur' }, { pattern: /\d+(\.[0-9]{1,2}){0,1}$/, message: '只能输入数字', trigger: 'change' }],
          fee: [{ required: true, message: '必填字段', trigger: 'blur' }, { pattern: /\d+(\.[0-9]{1,2}){0,1}$/, message: '只能输入数字,最多二位小数', trigger: 'change' }],
          warehouse_id: { required: true, message: '必填字段', trigger: 'blur' }
        },
        fields: [this.getColumn()]
      },
      type: '',
      disabled: '',
      maxLength: 1
    }
  },
  created() {
    const vm = this
    vm.id = vm.$route.query.id || ''
    vm.type = vm.$route.query.type || ''
    vm.disabled = vm.type === 'info'
    if (vm.id) {
      vm.handleUpdateNew(vm.id)
    }
    companyList().then((data) => {
      vm.optionCompany = data
    })
  },
  methods: {
    // 选择台阶费设置
    handleSelectMultiFather(data) {
      const vm = this
      vm.selectedIdsFather = []
      data.forEach(item => {
        vm.selectedIdsFather.push(item)
      })
    },
    // 批量删除已添加
    delField() {
      const vm = this
      const dataArr = [...this.model.fields]
      dataArr.map((arr) => {
        if (vm.selectedIdsFather.includes(arr)) {
          vm.model.fields.splice(vm.model.fields.indexOf(arr), 1)
        }
      })
    },
    handleCancelPath() {
      this.$router.push({ path: '/basics/orderFeeSetting' })
    },
    // 数据列表
    getColumn() {
      return {
        'min_weight': '',
        'max_weight': '',
        'fee': ''
      }
    },
    handleUpdateNew(id) {
      this.loading = true
      this.$http.get(`orderFeeSetting/${id}`).then(res => {
        const dataObj = res.data
        this.formFieldsData = dataObj
        if (dataObj.children && dataObj.children.length > 0 && dataObj.children[0].fee) {
          this.model.fields = dataObj.children.map((arr) => {
            arr.id = null
            arr.disabled = this.disabled
            return arr
          })
        }
        this.loading = false
        this.formVisible = true
      })
    },
    handleSubmitNew() {
      this.$refs['orderFeeSettings'].validate((valid) => {
        if (valid) {
          // 判断个人信息
          this.$refs['formData'].validate((validSon) => {
            // 添加
            if (validSon) {
              // 编辑
              if (this.formFieldsData.id) {
                this.$http.put(`orderFeeSetting/${this.formFieldsData.id}`, this.getData()).then(response => {
                  if (response.code === 10000) {
                    this.$message.success('编辑成功')
                    this.formVisible = false
                    this.$router.push({ path: '/basics/orderFeeSetting' })
                  } else {
                    this.$message.error(response.message)
                  }
                })
              } else {
                this.$http.post('orderFeeSetting', this.getData()).then(response => {
                  if (response.code === 10000) {
                    this.$message.success('添加成功')
                    this.formVisible = false
                    this.$router.push({ path: '/basics/orderFeeSetting' })
                  } else {
                    this.$message.error(response.message)
                  }
                })
              }
            }
          })
        }
      })
    },
    // 获取添加参数组合
    getData() {
      const data = Object.assign({}, this.formFieldsData)
      delete data.created_at
      delete data.updated_at
      if (this.model.fields && this.model.fields.length > 0) {
        const dataArr = this.model.fields.map((arr) => {
          if (arr.min_weight >= arr.max_weight) {
            arr.max_weight = arr.min_weight + 1
          }
          return {
            min_weight: arr.min_weight,
            max_weight: arr.max_weight,
            fee: arr.fee
          }
        })
        data['dataJson'] = JSON.stringify(dataArr)
      }
      return data
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
